<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/1/25
 * Time: 14:42
 */
namespace app\home\controller;
use think\Db;
class Index extends Base
{
    public function index(){
        if(isset($_REQUEST['did']) && $_REQUEST['did'] && isset($_REQUEST['ddd']) && $_REQUEST['ddd']){
            session('my_location_city_name', $_REQUEST['ddd']);
            session('my_location_city_id', $_REQUEST['did']);
        }
        //1、轮播图
        $lb = Db::name('lunbo')
            ->where(['lb_type'=>1,'lb_status'=>1])
            ->order('lb_time DESC')
            ->limit (3)
            ->select();
        //2、首页数据
        if(!session('?my_location_city_id')){
            $shi = 1002;
        }else{
            $shi = session('my_location_city_id');
        }
        $where['h_shi'] = $shi;
        $where['h_status'] = 1;
        $top1 = Db::table('up_top t')
            ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
            ->where($where)
            ->where('top_have_one',1)
            ->where('h_id','>',0)
            ->field(['h_id','h_xiaoqu','h_shis','h_tings','h_mianji','h_img','h_street','h_type','h_title','h_hot_title','h_price'])
            ->order('top_time ASC')
            ->limit (5)
            ->select ();
        //-----如果精选房源为空，则从置顶过的能拿出来的房源里随机选4个--start--
        if(!$top1){
            $hids_rand = Db::table('up_top t')
                ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
                ->where($where)
                ->where('h_id','>',0)
                ->group('top_h_id')
                ->order('top_time DESC')
                ->limit(0,100)
                ->column('top_id');
            if($hids_rand){
                if(count($hids_rand) > 5){
                    $hids = [];
                    $keys = array_rand($hids_rand,5);
                    foreach ($keys as $v){
                        $hids[] = $hids_rand[$v];
                    }
                }else{
                    $hids = $hids_rand;
                }
                $top1 = Db::table('up_top t')
                    ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
                    ->join ('up_area a','h.h_shi = a.district_id','LEFT')
                    ->where($where)
                    ->where('top_id','in',$hids)
                    ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','district','h_type'])
                    ->order('top_time ASC')
                    ->limit (5)
                    ->select ();
            }
        }
        //防止有重复的精选房源
        $chong_fu = [0];
        if($top1){
            foreach ($top1 as $k => $v){
                $chong_fu[] = $v['h_id'];
            }

        }
        //-----如果精选房源为空，则从置顶过的能拿出来的房源里随机选4个--end--
        $top2 = Db::table('up_house')
            ->where($where)
            ->where('h_have_top',1)
            ->where('h_id','not in',$chong_fu)
            ->field(['h_id','h_xiaoqu','h_shis','h_tings','h_mianji','h_img','h_street','h_type','h_title','h_hot_title','h_price'])
            ->order('h_time ASC')
            ->limit (5)
            ->select ();
        $top = array_merge($top1,$top2);
        $er = Db::table('up_top t')
            ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where($where)
            ->where('top_type',2)
            ->where('top_have_two',1)
            ->where('h_id','>',0)
            ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','district','h_type'])
            ->order('top_time ASC')
            ->limit (4)
            ->select ();
        $new = Db::table('up_house h')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where($where)
            ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','district','h_type'])
            ->order('h_time DESC')
            ->limit (4)
            ->select ();
        //-----如果二手房为空，则从置顶过的能拿出来的房源里随机选4个--start--
        if(!$er){
            $hids_rand = Db::table('up_top t')
                ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
                ->where($where)
                ->where('top_type',2)
                ->where('h_id','>',0)
                ->group('top_h_id')
                ->order('top_time DESC')
                ->limit(0,100)
                ->column('top_id');
            if($hids_rand){
                if(count($hids_rand) > 4){
                    $hids = [];
                    $keys = array_rand($hids_rand,4);
                    foreach ($keys as $v){
                        $hids[] = $hids_rand[$v];
                    }
                }else{
                    $hids = $hids_rand;
                }
                $er = Db::table('up_top t')
                    ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
                    ->join ('up_area a','h.h_shi = a.district_id','LEFT')
                    ->where($where)
                    ->where('top_id','in',$hids)
                    ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','district','h_type'])
                    ->order('top_time ASC')
                    ->limit (4)
                    ->select ();
            }
        }

        //-----如果二手房为空，则从置顶过的能拿出来的房源里随机选4个--end--
        //--------1、推荐楼盘和推荐装饰公司---------------
        $builds = Db::table('up_building')
            ->where('b_status',1)
            ->where('b_shi',$shi)
            ->order('b_tuijiang desc,b_updatetime desc')
            ->field('b_id,b_title,b_title_bottom,b_img,b_mianji_min,b_mianji_max,b_unit_price,b_is_sale,b_huxing,b_hot_title,b_address')
            ->page(1,4)
            ->select();
        $coms = Db::table('up_company')
            ->where('tuijian',1)
            ->where('shi',$shi)
            ->order('tuijian desc,time desc')
            ->field('id,address,thumb,name')
            ->page(1,4)
            ->select();
        //-------- end ------------------------------
        return $this->fetch ('index/home_page',[
            'top'=>$top,'er'=>$er,'new'=>$new,'lb'=>$lb
            ,'builds'=>$builds,'coms'=>$coms
        ]);
    }
    /**
     * 搜索:getSearchList
     * type：1是出租（出租），2是出售（二手房和新房）
     * shi：当前定位的市id
     */
    public function searchResult()
    {
        extract(input());
        $shi = session('my_location_city_id');
        $search = input('param.search/a');
        $page = input('param.page');
        $where = array();
        if(isset($_REQUEST['type'])){
            $search[0] = $_REQUEST['type'];
        }
        if(isset($_REQUEST['keyword'])){
            $search[1] = $_REQUEST['keyword'];
        }
        $search = $this->search($search, $page);
        if($search[0] != ""){
            $type = $search[0];
        }else{
            $type = $_REQUEST['type'];
        }
        if($search[1] != ""){
            $keyword = $search[1];
        }else{
            $keyword = $_REQUEST['keyword'];
        }
        if($type == 3){
            $where = [];
            if(isset($keyword) && $keyword){
                $where['dis_name'] = ['like','%'.$keyword.'%'];
            }
            $data = Db::table('up_district')
                ->where($where)
                ->order('dis_update DESC')
                ->paginate(15);
        }else{
            $where['h_shi'] = $shi;
            $where['h_type'] = $type;
            $where['h_status'] = 1;
            if($type == 2){
                $where['h_type'] = array('in','2,3');
            }
            $data = Db::table('up_house h')
                ->join ('up_area a','h.h_shi = a.district_id','LEFT')
                ->where($where)
                ->where (function ($query) use ($keyword){
                    $query->where( 'h_xiaoqu',"like","%$keyword%")->whereOr( 'h_title',"like","%$keyword%");
                })
                ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','district','h_sign'])
                ->order('h_order DESC,h_time DESC')
                ->paginate(15);
        }
        $types = [1=>'免税', 2=>'精装',3=>'学区房',4=>'配套完善',5=>'低首付',6=>'方便停车',7=>'环境优美',
            8=>'急售',9=>'婚房',10=>'短租', 11=>'拎包入住',12=>'精装修',13=>'配套完善',
            14=>'可供暖',15=>'停车方便'];
        return $this->fetch ('index/search',['data'=>$data,'types'=>$types,'search'=>$search]);
    }
    /**
     * 房源详情：houseInfo
     * h_id：房子id
     */
    public function houseInfo()
    {
        extract(input());
        $user_id = session('user_id');
        $data = Db::table('up_house h')
            ->join ('up_u_user u','h.h_user_id = u.user_id','LEFT')
            ->where('h_id',$h_id)
            ->field('h.*,user_username,user_image,user_shop,user_ercode')
            ->find ();
        $data['h_jianjie'] = nl2br($data['h_jianjie']);
        if(!$data){
            return json(['status'=>0,'msg'=>'该房源信息已被删除']);
        }
        $have = Db::table('up_like')
            ->where('like_user_id',$user_id)
            ->where('like_h_id',$h_id)
            ->find ();
        $data['h_images'] = explode(',',$data['h_images']);
        $data['h_sign'] = explode(',',trim($data['h_sign'],','));
        if($data['h_more']){
            $data['h_more'] = explode(',',trim($data['h_more'],','));
        }
        $like = 0;
        if($have){
            $like = 1;//已关注
        }
        //入历史记录----start-----
        if(session('?user_id')){
            $insert = array();
            $insert['his_user_id'] = $user_id;
            $insert['his_h_id'] = $h_id;
            Db::table('up_history')->where($insert)->delete();
            $insert['his_date'] = date('Y-m-d H:i:s');
            Db::table('up_history')->insert($insert);
        }
        //入历史记录----end-------
        //------------推荐房源-------------------
//        if(!session('?my_location_city_id')){
//            $shi = 1002;
//        }else{
//            $shi = session('my_location_city_id');
//        }
//        $where = array();
//        $where['h_shi'] = $shi;
//        $where['h_status'] = 1;
//        $tuijian = array();
//        $hids_rand = Db::table('up_top t')
//            ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
//            ->where($where)
//            ->where('top_type',$data['h_type'])
//            ->where('h_id','>',0)
//            ->group('top_h_id')
//            ->order('top_time DESC')
//            ->limit(0,100)
//            ->column('top_id');
//        if($hids_rand){
//            if(count($hids_rand) > 4){
//                $hids = [];
//                $keys = array_rand($hids_rand,4);
//                foreach ($keys as $v){
//                    $hids[] = $hids_rand[$v];
//                }
//            }else{
//                $hids = $hids_rand;
//            }
//            $tuijian = Db::table('up_top t')
//                ->join ('up_house h','t.top_h_id = h.h_id','LEFT')
//                ->join ('up_area a','h.h_shi = a.district_id','LEFT')
//                ->where('top_id','in',$hids)
//                ->field(['h_id','h_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type'])
//                ->select ();
//        }
        //---------------end-------------------
        $fix = ['未知','简装','中装','精装','毛坯'];
        $mores = [1=>'车位', 2=>'电梯',3=>'车库',4=>'花园',5=>'储藏室',6=>'阁楼',7=>'床',
            8=>'沙发',9=>'电视',10=>'冰箱', 11=>'热水器',12=>'空调'];
//
        //---1、贷款
        $daikuan = [
            'yuegong' => 0,
            'lixi' => 0,
            'shoufu' => 0,
            'dai' => 0,
            'zuzu' => 0
        ];
        if($data['h_type'] > 1){
            if($data['h_price'] >= 10000){
                $data['h_price'] = round($data['h_price']/10000,2);
            }
            $daikuan['allprice'] = $data['h_price'];
            $daikuan['shoufu'] = round(($data['h_price'] * $data['h_first'])/100,2);
            $daikuan['dai'] = $daikuan['allprice'] - $daikuan['shoufu'];
            $dknl = Db::table('up_about')->where('id',4)->value('content');
            $mww_dk =  new \app\api\controller\Show();
            $res = $mww_dk->debx(360,$daikuan['dai']*10000,$dknl);
            $daikuan['lixi'] = round($res['alllixi']/10000);
            $daikuan['yuegong'] = $res['data'][0]['month'];
            $daikuan['zuzu'] = 1;
        }
        //---2、所属小区信息
        $xiaoqu = [];
        if($data['h_dis_id'] > 0){
            $xiaoqu = Db::table('up_district')->where('dis_id',$data['h_dis_id'])->find();
        }
        //---3、装修风格推荐
        $cases = [];
        if($data['h_type'] > 1){
            $cases = Db::table('up_company_case')
                ->order('cc_time DESC')
                ->field('cc_id,cc_style,cc_thumb')
                ->page(1,4)
                ->select();
        }
        //---4、同小区经纪人推荐
        $tjuser = [];
        if($data['h_dis_id'] > 0){
            $uids = Db::table('up_house')
                ->where('h_type',$data['h_type'])
                ->where('h_status',1)
                ->where('h_dis_id',$data['h_dis_id'])
                ->where('h_user_id',"<>",$data['h_user_id'])
                ->column('h_user_id');

            if($uids){
                $tjuser =  Db::table('up_u_user')
                    ->where('user_type',2)
                    ->where('user_status',1)
                    ->where('user_id',"in",$uids)
                    ->order('user_reject_time DESC')
                    ->field('user_id,user_username,user_shop,user_image,user_phone,user_ercode')
                    ->page(1,4)
                    ->select();
            }

        }
        //---5、同小区房源推荐
        $tjhouse = [];
        if($data['h_dis_id'] > 0){
            $tjhouse = Db::table('up_house h')
                ->join ('up_area a','h.h_shi = a.district_id','LEFT')
                ->where('h_type',$data['h_type'])
                ->where('h_status',1)
                ->where('h_dis_id',$data['h_dis_id'])
                ->where('h_id',"<>",$data['h_id'])
                ->order('h_time DESC')
                ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','district'])
                ->page(1,10)
                ->select();
        }
//
        return $this->fetch ('index/listDetails',['data'=>$data,'like'=>$like,
            'fix'=>$fix,'mores'=>$mores
            , 'daikuan' => $daikuan
            , 'xiaoqu' => $xiaoqu
            , 'cases' => $cases
            , 'tjuser' => $tjuser
            , 'tuijian' => $tjhouse
        ]);
    }
    /**
     * 关注或取消关注此房源：houseLike
     * h_id：房子id
     */
    public function houseLikeOrNo()
    {
        extract(input());
        if(!session('?user_id')){
            return json(['status'=>404,'msg'=>'请登录！']);
        }
        $user_id = session('user_id');
        $have = Db::table('up_like')
            ->where('like_user_id',$user_id)
            ->where('like_h_id',$h_id)
            ->find ();
        $now = 1;
        if($have){
            $res = Db::table('up_like')
                ->where('like_user_id',$user_id)
                ->where('like_h_id',$h_id)
                ->delete ();
        }else{
            $now = 2;
            $data = array();
            $data['like_user_id'] = $user_id;
            $data['like_h_id'] = $h_id;
            $res = Db::table('up_like')->insert($data);
        }
        if($res){
            return json(['status'=>200,'now'=>$now,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }

    }
    /**
     * 定位列表
     */
    public function position()
    {
        extract(input());
        $citys = Db::table('up_area')->where('level',2)->select();
        $data = array();
        foreach ($citys as $k=>$v){
            $str = $v['district'];
            $str= iconv("UTF-8","gb2312", $str);
            $tmp=bin2hex(substr($str,0,1));
            if($tmp>='B0'){ //汉字的开始
                $t=$this->getLetter(hexdec(bin2hex(substr($str,0,2))));
                $letter = chr($t);
                if($v['district'] == '衢州市'){$letter = 'Q';}
                if($v['district'] == '亳州市'){$letter = 'B';}
                if($v['district'] == '濮阳市'){$letter = 'P';}
                if($v['district'] == '漯河市'){$letter = 'L';}
                if($v['district'] == '儋州市'){$letter = 'D';}
                if($v['district'] == '泸州市'){$letter = 'L';}
                $data[$k]['id'] = $v['district_id'];
                $data[$k]['name'] = $v['district'];
                $data[$k]['letter'] = $letter;
                $data[$k]['me'] = 1;
                if(session('my_location_city_id') == $v['district_id']){
                    $data[$k]['me'] = 2;
                }
            }
        }
        $last_names = array_column($data,'letter');
        array_multisort($last_names,SORT_ASC,$data);
        $start = '';
        $res = array();
        foreach ($data as $k=>$v){
            if($v['letter'] != $start){
                $start = $v['letter'];
            }
            $res[$start][] = $v;

        }
        //--------------------
        $hot = Db::table('up_area')
            ->where('level',2)
            ->where('hot',2)
            ->select();
//        dump($res['A']);die;
        return $this->fetch ('index/position',['data'=>$res,'hot'=>$hot]);
    }
    public function getLetter($num){
        $limit = array( //gb2312 拼音排序
            array(45217,45252), //A
            array(45253,45760), //B
            array(45761,46317), //C
            array(46318,46825), //D
            array(46826,47009), //E
            array(47010,47296), //F
            array(47297,47613), //G
            array(47614,48118), //H
            array(0,0),     //I
            array(48119,49061), //J
            array(49062,49323), //K
            array(49324,49895), //L
            array(49896,50370), //M
            array(50371,50613), //N
            array(50614,50621), //O
            array(50622,50905), //P
            array(50906,51386), //Q
            array(51387,51445), //R
            array(51446,52217), //S
            array(52218,52697), //T
            array(0,0),     //U
            array(0,0),     //V
            array(52698,52979), //W
            array(52980,53688), //X
            array(53689,54480), //Y
            array(54481,55289), //Z
        );
        $char_index=65;
        foreach($limit as $k=>$v){
            if($num>=$v[0] && $num<=$v[1]){
                $char_index+=$k;
                return $char_index;
            }
        }
        return -1;
    }

    /**
     * 急售的那四个的数据列表
     *
     * shi：当前定位的市id
     */
    public function four()
    {
        extract(input());
        if(!session('?my_location_city_id')){
            $shi = 1002;
        }else{
            $shi = session('my_location_city_id');
        }

        $search = input('param.search/a');
        $page = input('param.page');
        $where = array();
        if(isset($_REQUEST['sign'])){
            $search[0] = $_REQUEST['sign'];
        }
        $search = $this->search($search, $page);
        if($search[0] != ""){
            $sign = $search[0];
        }else{
            $sign = $_REQUEST['sign'];
        }
        $where['h_sign'] = array('like','%,'.$sign.',%');
        $where['h_shi'] = $shi;
        $where['h_status'] = 1;
        $data = Db::table('up_house h')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where($where)
            ->field(['h_id','h_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','h_sign','district'])
            ->order('h_time DESC')
            ->paginate(25);
        //----------------------------
        //----------------------------
        $types = [1=>'免税', 2=>'精装',3=>'学区房',4=>'配套完善',5=>'低首付',6=>'方便停车',7=>'环境优美',8=>'急售',9=>'婚房'];
        //----------------------------
        $signs = [4=>'学区房',5=>'低首付',8=>'急售',9=>'婚房'];
        //----------------------------
        return $this->fetch ('list/jishou',['data'=>$data,'sign'=>$sign,'signs'=>$signs,'types'=>$types]);
    }
    /**
     * 所有的新房源
     * shi：当前定位的市id
     */
    public function allNerHouses()
    {
        extract(input());
        $shi = session('my_location_city_id');
        $where['h_shi'] = $shi;
        $where['h_status'] = 1;
        $data = Db::table('up_house h')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where($where)
            ->field(['h_id','h_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','h_sign','district'])
            ->order('h_time DESC')
            ->paginate(20);
        //----------------------------
        //----------------------------
        $types = [1=>'免税', 2=>'精装',3=>'学区房',4=>'配套完善',5=>'低首付',6=>'方便停车',7=>'环境优美',
            8=>'急售',9=>'婚房',10=>'短租', 11=>'拎包入住',12=>'精装修',13=>'配套完善',
            14=>'可供暖',15=>'停车方便'];
        //----------------------------
        return $this->fetch ('list/all',['data'=>$data,'types'=>$types]);
    }


    //---------------------------------------------------------------------------------------------
    /**
     * 小区详情
     *
     */
    public function disInfo(){
        extract(input());
        $where = array();
        $where['dis_id'] = $dis_id;
        $data = Db::table('up_district')
            ->where($where)
            ->find ();
        if(!$data){
            echo '此小区不存在或已下架！';
            die;
        }
        //轮播图
        if($data['dis_images']){
            $data['dis_images'] = explode(',',$data['dis_images']);
        }
        //户型图和推荐
        $huxings = Db::table('up_district_hu')
            ->where('dh_type',1)
            ->where('dh_dis_id',$dis_id)
            ->page(1,5)
            ->select();
        //---4、同小区经纪人推荐
        $uids = Db::table('up_house')
            ->where('h_status',1)
            ->where('h_dis_id',$dis_id)
            ->column('h_user_id');
        $tjuser =  Db::table('up_u_user')
            ->where('user_type',2)
            ->where('user_status',1)
            ->where('user_id',"in",$uids)
            ->order('user_reject_time DESC')
            ->field('user_id,user_username,user_shop,user_image,user_phone,user_ercode')
            ->page(1,4)
            ->select();
        //---5、同小区二手房源推荐
        $tjerhouse = Db::table('up_house h')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where('h_type',2)
            ->where('h_status',1)
            ->where('h_dis_id',$dis_id)
            ->order('h_time DESC')
            ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','district'])
            ->page(1,4)
            ->select();
        //---5、同小区租户房源推荐
        $tjzuhouse = Db::table('up_house h')
            ->join ('up_area a','h.h_shi = a.district_id','LEFT')
            ->where('h_type',1)
            ->where('h_status',1)
            ->where('h_dis_id',$dis_id)
            ->order('h_time DESC')
            ->field(['h_id','h_title','h_hot_title','h_xiaoqu','h_price','h_shis','h_tings','h_mianji','h_img','h_type','district'])
            ->page(1,4)
            ->select();
        $mf_img = Db::table('up_about')
            ->where('id',5)
            ->value ('content');
        $fetch = [
            'data'=>$data,'huxings'=>$huxings
            ,'tjuser'=>$tjuser
            ,'tjerhouse'=>$tjerhouse
            ,'tjzuhouse'=>$tjzuhouse
            ,'mf_img'=>$mf_img
        ];
        return $this->fetch ('index/disinfo',$fetch);
    }
}